<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OADept;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class DeptLogic
 * @package App\Http\Controllers\Logic
 * @desc 部门操作逻辑
 */
class DeptLogic extends Controller
{
    //获取部门列表
    public function deptList($input)
    {
        $query = OADept::query();
        //id存在时
        if($id=$input['id']){
            $query->when($id,function($q,$id){
                return $q->where('id',$id);
            });
        }
        //name存在
        if($name=$input['name']){
           $query->when($name,function($q,$name){
              return $q->where('name','like','%'.$name.'%');
           });
        }
        //key 存在
        if($key=$input['key']){
            $query->when($key,function($q,$key){
                return $q->where('key','like','%'.$key.'%');
            });
        }

        $pagNum = $input['pageNum'] ? $input['pageNum'] : 5;
        try{
            return $query->paginate($pagNum,['*'])->toArray();
        }catch(\Exception $e){
            throw new \Exception($query->toSql());
        }


    }

    //编辑部门
    public function editDept($input)
    {
        DB::beginTransaction();
        try {
            $dept = OADept::where('id',$input['id'])->first();
            $dept->title = $input['name'];
            $dept->short_name = $input['key'];
            $dept->status = $input['state'];
            $dept->save();
            DB::commit();
            return true;
        }catch(\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //新增部门
    public function addDept($input)
    {

        try {

            if(OADept::where('title',$input['name'])->exists()) throw new \Exception('部门已存在,请勿重复添加');
            $dept = new OADept();
            $dept->title = $input['name'];
            $dept->short_name = $input['key'];
            $dept->status = $input['state'];
            $dept->created_at = date('Y-m-d H:i:sd');
            $dept->save();
            return $dept->id;
        }catch (\Exception $e){
            throw new \Exception('部门新增失败');
        }

    }
}
